package com.service.component.user.controller;

import com.service.component.common.CommonResult;
import com.service.component.common.enumerate.OperateTypeEnum;
import com.service.component.common.utils.CommonUtils;
import com.service.component.common.utils.VerifyCodeUtils;
import com.service.component.log.aspect.SysOperateLog;
import com.service.component.relation.entity.UserFilterPermRelation;
import com.service.component.relation.entity.UserFilterRoleRelation;
import com.service.component.relation.services.RelationServices;
import com.service.component.user.entity.Users;
import com.service.component.user.services.UserServices;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;


/**
 * @author ：Calvin
 * @date ：Created in 2021/7/16 14:35
 * @description：用户管理
 * @modified By：
 * @version: 1.0.0$
 */
@Slf4j
@RestController
@Api(value = "用户管理")
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserServices userServices;

    @Autowired
    private RelationServices relationServices;

    @PostMapping("register")
    @ApiOperation(value = "用户注册", notes = "用户注册")
    @SysOperateLog(descrption = "新用户注册",operateType = OperateTypeEnum.ADD)
    public CommonResult register(@RequestBody  Users users){
        Users userByUsername = userServices.getUserByUsername(users.getUsername());
        if(ObjectUtils.isEmpty(userByUsername)){
            return userServices.register(users);
        }
        return CommonResult.commonResult(CommonResult.ResultCode.DATA_EXIST);
    }

    @PostMapping("login")
    @ApiOperation(value = "用户登录", notes = "用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true, paramType = "path"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, paramType = "path")
    })
    @SysOperateLog(descrption = "登录操作", operateType = OperateTypeEnum.QUERY)
    public CommonResult login(String username, String password) {
        return userServices.login(username, password);
    }

    @GetMapping("getValidateCode")
    @ApiOperation(value = "生成验证码", notes = "生成验证码")
    public void getValidateCode() throws IOException {
        String securityCode = VerifyCodeUtils.getSecurityCode();
        CommonUtils.getHttpSession().setAttribute(VerifyCodeUtils.LOGIN_VALIDATE_CODE, securityCode);
        BufferedImage image = VerifyCodeUtils.createImage(securityCode);
        ServletOutputStream outputStream = CommonUtils.getHttpServletResponse().getOutputStream();
        ImageIO.write(image, "png", outputStream);
    }

    @GetMapping("/checkValidateCode/{validateCode}")
    @ApiOperation(value = "检查验证码是否正确", notes = "检查验证码是否正确")
    @SysOperateLog(descrption = "检查验证码是否正确", operateType = OperateTypeEnum.QUERY)
    @ApiImplicitParam(name = "validateCode", value = "输入的验证码", required = true, paramType = "path")
    public CommonResult checkValidateCode(@Valid @PathVariable @NotBlank(message = "validateCode不能为空") String validateCode) {
        return CommonResult.commonResult(VerifyCodeUtils.checkValidateCode(validateCode));
    }

    @ApiOperation(value = "查询全部用户信息", notes = "查询全部用户信息")
    @RequiresPermissions("get")
    @RequiresRoles("reader")
    @GetMapping(value = "getUserByUser", produces = {"application/json;charset=UTF-8"})
    @SysOperateLog(descrption = "查询全部用户信息", operateType = OperateTypeEnum.QUERY)
    public List<Users> getUser(Users users) {
        return userServices.getUser(users);
    }


    @RequiresPermissions(value={"get","all"},logical= Logical.OR)
    @ApiOperation(value = "根据userId查询username", notes = "根据userId查询username")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "path")
    @GetMapping(value = "getUserName/{userId}", produces = {"application/json;charset=UTF-8"})
    @SysOperateLog(descrption = "根据userId查询username", operateType = OperateTypeEnum.QUERY)
    public String getUserNameByUserName(@Valid @PathVariable @NotBlank(message = "userId不能为空") String userId) {
        return userServices.getUserName(userId);
    }

    @ApiOperation(value = "新增或者修改用户负角色", notes = "新增或者修改用户负角色")
    @PostMapping(value = "insertUserFilterRole", produces = {"application/json;charset=UTF-8"})
    @SysOperateLog(descrption = "新增或者修改用户负角色", operateType = OperateTypeEnum.ADD)
    public CommonResult insertUserFilterRole(@RequestBody  UserFilterRoleRelation userFilterRoleRelation) {
        return relationServices.insertOrUpdateRelation(userFilterRoleRelation);
    }

    @ApiOperation(value = "新增或者修改用户负权限", notes = "新增或者修改用户负权限")
    @PostMapping(value = "insertUserFilterPerm", produces = {"application/json;charset=UTF-8"})
    @SysOperateLog(descrption = "新增或者修改用户负权限", operateType = OperateTypeEnum.ADD)
    public CommonResult insertUserFilterPerm(@RequestBody UserFilterPermRelation userFilterPermRelation) {
        return relationServices.insertOrUpdateRelation(userFilterPermRelation);
    }
}
